<template>
  <input
    class="xueyanInput"
    :disabled="disabled"
    :readonly="readonly"
    :type="type"
    v-model="val"
    :style="styleBuilder"
    @onkeyup="regTest(regexp)"
    @focus="focus"
    @blur="blur"
  />
</template>
<script lang="ts" setup>
  import { computed, watch, ref, onMounted, reactive } from 'vue'

  const props = defineProps({
    modelValue: String,
    size: String,
    type: {
      type: String,
      default: 'text'
    },
    readonly: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    regexp: {
      type: String,
      default: ''
    }
  })

  const emit = defineEmits(['update:modelValue','change','focus','blur'])

  const focus = () => {
    emit('focus')
  }

  const blur = () => {
    emit('blur')
  }

  const val: any = ref('')
  const styleBuilder = computed(() => {
    let styleObj: any = {}
    switch (props.size) {
      case 'mini':
        styleObj.fontSize = '8px'
        break
      case 'large':
        styleObj.fontSize = '18px'
        break
      case 'superlarge':
        styleObj.fontSize = '20px'
        break
      case 'small':
        styleObj.fontSize = '12px'
        break
      default:
        styleObj.fontSize = '16px'
        break
    }
    if (props.disabled) {
      styleObj.backgroundColor = '#EEE'
      styleObj.borderColor = '#BBB'
      styleObj.cursor = 'not-allowed'
    }
    if (props.readonly) {
      styleObj.borderColor = '#BBB'
      styleObj.cursor = 'not-allowed'
    }
    return styleObj
  })

  const regTest = (regexp: string) => {
    if (regexp === '') {
      return
    } else {
      val.value = val.value.replace(regexp)
    }
  }

  watch(val, () => {
    emit('update:modelValue', val.value)
    emit('change')
  })

  onMounted(() => {
    val.value = props.modelValue
  })
</script>
<style scoped>
  .xueyanInput {
    cursor: text;
    border-radius: 5px;
    border: 1px solid #87ceeb;
    outline-style: none;
    padding: 7px 0px;
  }
  .xueyanInput:focus,
  .xueyanInput:hover {
    filter: drop-shadow(0 0 3px #87ceebaa);
  }
</style>
